// pages/login/login.js
Page({
  data: {
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    hasUserInfo: false,
    userInfo: {},
    loading: false
  },

  onLoad: function (options) {
    // 检查是否已经授权
    this.checkUserInfo();
  },

  // 检查用户信息
  checkUserInfo: function () {
    const app = getApp();
    if (app.globalData.userInfo) {
      this.setData({
        hasUserInfo: true,
        userInfo: app.globalData.userInfo
      });
    }
  },

  // 微信登录 - 直接进入应用
  onWechatLogin: function () {
    const app = getApp();
    const self = this;
    
    // 设置loading状态
    this.setData({ loading: true });
    
    // 模拟登录成功，直接设置用户信息
    setTimeout(() => {
      // 设置默认用户信息
      const mockUserInfo = {
        nickName: '微信用户',
        avatarUrl: '/images/default-avatar.png',
        gender: 1,
        country: '中国',
        province: '广东',
        city: '深圳'
      };
      
      // 保存用户信息到全局
      app.globalData.userInfo = mockUserInfo;
      app.globalData.token = 'mock_token_' + Date.now();
      app.globalData.userId = 'mock_user_' + Date.now();
      app.globalData.isGuest = false;
      
      // 保存到本地存储
      wx.setStorageSync('userInfo', mockUserInfo);
      wx.setStorageSync('token', app.globalData.token);
      wx.setStorageSync('userId', app.globalData.userId);
      wx.setStorageSync('isGuest', false);
      
      // 更新页面状态
      self.setData({
        hasUserInfo: true,
        userInfo: mockUserInfo,
        loading: false
      });
      
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      // 延迟跳转到首页
      setTimeout(() => {
        const pages = getCurrentPages();
        if (pages.length > 1) {
          wx.navigateBack();
        } else {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }
      }, 1000);
    }, 500);
  },

  // 微信登录API调用 - 等待后续开启
  wechatLogin: function (code, userInfo) {
    const app = getApp();
    const self = this;
    
    // TODO: 调用后端微信登录API
    wx.request({
      url: app.globalData.apiBase + '/api/auth/wechat-login',
      method: 'POST',
      data: {
        code: code,
        userInfo: userInfo
      },
      success: function (res) {
        if (res.data.code === 0) {
          // 保存用户信息到全局
          app.globalData.userInfo = res.data.data.userInfo;
          app.globalData.token = res.data.data.token;
          app.globalData.userId = res.data.data.userId;
          app.globalData.isGuest = false;
          
          // 保存到本地存储
          wx.setStorageSync('userInfo', res.data.data.userInfo);
          wx.setStorageSync('token', res.data.data.token);
          wx.setStorageSync('userId', res.data.data.userId);
          wx.setStorageSync('isGuest', false);
          
          self.setData({
            hasUserInfo: true,
            userInfo: res.data.data.userInfo,
            loading: false
          });
          
          wx.showToast({
            title: '登录成功',
            icon: 'success'
          });
          
          // 延迟跳转
          setTimeout(() => {
            const pages = getCurrentPages();
            if (pages.length > 1) {
              wx.navigateBack();
            } else {
              wx.switchTab({
                url: '/pages/index/index'
              });
            }
          }, 1500);
        } else {
          self.setData({ loading: false });
          wx.showToast({
            title: res.data.message || '登录失败',
            icon: 'none'
          });
        }
      },
      fail: function () {
        self.setData({ loading: false });
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        });
      }
    });
  },

  // Mock登录 - 用于测试
  mockLogin: function (code, userInfo) {
    const app = getApp();
    const self = this;
    
    // 模拟API响应
    setTimeout(() => {
      const mockResponse = {
        code: 0,
        data: {
          userInfo: {
            nickName: userInfo.nickName,
            avatarUrl: userInfo.avatarUrl,
            gender: userInfo.gender,
            country: userInfo.country,
            province: userInfo.province,
            city: userInfo.city
          },
          token: 'mock_token_' + Date.now(),
          userId: 'mock_user_' + Date.now()
        },
        message: '登录成功'
      };
      
      // 保存用户信息到全局
      app.globalData.userInfo = mockResponse.data.userInfo;
      app.globalData.token = mockResponse.data.token;
      app.globalData.userId = mockResponse.data.userId;
      app.globalData.isGuest = false;
      
      // 保存到本地存储
      wx.setStorageSync('userInfo', mockResponse.data.userInfo);
      wx.setStorageSync('token', mockResponse.data.token);
      wx.setStorageSync('userId', mockResponse.data.userId);
      wx.setStorageSync('isGuest', false);
      
      self.setData({
        hasUserInfo: true,
        userInfo: mockResponse.data.userInfo,
        loading: false
      });
      
      wx.showToast({
        title: '登录成功',
        icon: 'success'
      });
      
      // 延迟跳转
      setTimeout(() => {
        const pages = getCurrentPages();
        if (pages.length > 1) {
          wx.navigateBack();
        } else {
          wx.switchTab({
            url: '/pages/index/index'
          });
        }
      }, 1500);
    }, 1000);
  },

  // 用户协议
  onUserAgreement: function () {
    wx.showModal({
      title: '用户协议',
      content: '这里是用户协议的内容...',
      showCancel: false
    });
  },

  // 隐私政策
  onPrivacyPolicy: function () {
    wx.showModal({
      title: '隐私政策',
      content: '这里是隐私政策的内容...',
      showCancel: false
    });
  }
});